<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta property="og:type" content="website">
<meta property="og:title" content="vhuichen">
<meta property="og:url" content="https://vhuichen.github.io/page/7/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:locale">
<meta property="article:author" content="vhuichen">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/page/7/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":true,"isPost":false,"lang":"zh-Hans","comments":"","permalink":"","path":"page/7/index.html","title":""}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">vhuichen</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-overview-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner index posts-expand">

    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E5%B0%BE%E8%B0%83%E7%94%A8%E4%BC%98%E5%8C%96/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%E5%B0%BE%E8%B0%83%E7%94%A8%E4%BC%98%E5%8C%96/" class="post-title-link" itemprop="url">尾调用优化</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-21 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-21T00:00:00+08:00">2018-04-21</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:15:54" itemprop="dateModified" datetime="2018-07-01T16:15:54+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="序言"><a href="#序言" class="headerlink" title="序言"></a>序言</h1><p>看《Effective Objective-C 2.0》这本书发现“尾调用”这个词汇，之前没接触过，记录下来。</p>
<h3 id="什么是尾调用"><a href="#什么是尾调用" class="headerlink" title="什么是尾调用"></a>什么是尾调用</h3><p>“尾调用”是指一个函数的最后一项操作是调用另一个函数，即被调用函数的返回值就是当前函数的返回值。例如：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)func0:(<span class="type">int</span>)i &#123;</span><br><span class="line">    <span class="comment">// do anything</span></span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> func1:i];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">int</span>)func0:(<span class="type">int</span>)i &#123;</span><br><span class="line">    <span class="comment">// do anything</span></span><br><span class="line">    <span class="keyword">if</span> (i == <span class="number">0</span>) &#123;</span><br><span class="line">    	<span class="keyword">return</span> [<span class="keyword">self</span> func2:i];</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> [<span class="keyword">self</span> func1:i];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面的例子不属于尾调用</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)func0:(<span class="type">int</span>)i &#123;</span><br><span class="line">    <span class="comment">// do anything</span></span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> func1:i] + <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">int</span>)func0:(<span class="type">int</span>)i &#123;</span><br><span class="line">    <span class="comment">// do anything</span></span><br><span class="line">    <span class="type">int</span> value = [<span class="keyword">self</span> func1:i]</span><br><span class="line">    <span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="尾递归"><a href="#尾递归" class="headerlink" title="尾递归"></a>尾递归</h3><p>如果函数在尾部调用的是自身，那么就叫做“尾递归”。    </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)func0:(<span class="type">int</span>)i &#123;</span><br><span class="line">    <span class="comment">// do anything</span></span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> func0:i];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="尾调用优化"><a href="#尾调用优化" class="headerlink" title="尾调用优化"></a>尾调用优化</h3><p>当一个函数是尾调用时，那么当前函数开辟的栈空间就已经不需要再使用了。被调用函数不需要开辟新的栈空间，而是直接使用当前函数的栈空间（更新原有栈），再把被调用函数的返回地址替换成当前函数的返回地址，这就是“尾调用优化”。使用“尾调用优化”技术，可以避免栈溢出。 </p>
<h3 id="尾递归优化（例子）"><a href="#尾递归优化（例子）" class="headerlink" title="尾递归优化（例子）"></a>尾递归优化（例子）</h3><blockquote>
<p>求n!</p>
</blockquote>
<p>没有使用尾调用时代码是这样写的：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)factorial0:(<span class="type">int</span>)n &#123;</span><br><span class="line">    <span class="keyword">if</span> (n &lt; <span class="number">1</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (n == <span class="number">1</span>) <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> n * [<span class="keyword">self</span> factorial0:n - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>程序第一次进入 factorial0 函数时需要在栈中分配内存用来保存 n 值。然后在每一次递归调用 factorial0 时都需要再分配新的内存来保存新的变量 n（这里的每一个 n 值都是不一样的，内存也是不一样的），空间复杂度O(n)。这样栈就会一直叠加，最后可能造成栈溢出。  </p>
<p>使用了尾调用时代码是这样写的：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)factorial1:(<span class="type">int</span>)n &#123;</span><br><span class="line">    <span class="keyword">if</span> (n &lt; <span class="number">1</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> factorial1:n total:<span class="number">1</span>];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">int</span>)factorial1:(<span class="type">int</span>)n total:(<span class="type">int</span>)total &#123;</span><br><span class="line">    <span class="keyword">if</span> (n == <span class="number">1</span>) <span class="keyword">return</span> total;</span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">self</span> factorial1:n - <span class="number">1</span> total:total * n];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>factorial1 只执行一次，不影响，空间复杂度O(1)。<br>程序第一次进入 factorial1:count 函数时需要在栈中分配内存用来保存 n 值。当第二次调用 factorial1:count 时，由于是尾调用，此时第一次分配的栈空间已经不需要再用了，所以第二次调用的时候直接使用原有栈，不需要分配额外的内存。空间复杂度O(1)。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(2)/" class="post-title-link" itemprop="url">《Effective Objective-C 2.0》第二章阅读笔记(2)</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-20 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-20T00:00:00+08:00">2018-04-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:15:15" itemprop="dateModified" datetime="2018-07-01T16:15:15+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第二章：对象、消息、运行期-2"><a href="#第二章：对象、消息、运行期-2" class="headerlink" title="第二章：对象、消息、运行期(2)"></a><center>第二章：对象、消息、运行期(2)</center></h1><h2 id="第9条：以-“类族模式”-模式隐藏实现细节"><a href="#第9条：以-“类族模式”-模式隐藏实现细节" class="headerlink" title="第9条：以 “类族模式” 模式隐藏实现细节"></a>第9条：以 “类族模式” 模式隐藏实现细节</h2><p>类族模式可以把实现细节隐藏在一套简单的公共接口后面。Objective-C 的系统框架普遍使用此模式。例如：UIButton NSArray NSNumber 等等。</p>
<h4 id="自定义-“类族模式”"><a href="#自定义-“类族模式”" class="headerlink" title="自定义 “类族模式”"></a>自定义 “类族模式”</h4><p>定义一个 Person 基类以及三个子类 PersonA, PersonB, PersonC 。三个子类分别实现自己的 doWork 任务。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Person</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">Person</span> : <span class="title">NSObject</span></span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)personWithType:(PersonType)personType;</span><br><span class="line">- (<span class="type">void</span>)doWork;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">Person</span></span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)personWithType:(PersonType)personType &#123;</span><br><span class="line">    <span class="keyword">switch</span> (personType) &#123;</span><br><span class="line">        <span class="keyword">case</span> PersonTypeA:</span><br><span class="line">            <span class="keyword">return</span> [PersonA new];</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> PersonTypeB:</span><br><span class="line">            <span class="keyword">return</span> [PersonB new];</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> PersonTypeC:</span><br><span class="line">            <span class="keyword">return</span> [PersonC new];</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)doWork &#123;</span><br><span class="line">    <span class="comment">//SubClasses implement this</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// Subclass PersonA</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">PersonA</span> : <span class="title">Person</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">PersonA</span></span></span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)doWork &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;do PersonA Work&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// Subclass PersonB</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">PersonB</span> : <span class="title">Person</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">PersonB</span></span></span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)doWork &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;do PersonB Work&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// Subclass PersonC</span></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">PersonC</span> : <span class="title">Person</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">PersonC</span></span></span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)doWork &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;do PersonC Work&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>接口调用如下：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">Person *personA = [Person personWithType:PersonTypeA];</span><br><span class="line">Person *personB = [Person personWithType:PersonTypeB];</span><br><span class="line">Person *personC = [Person personWithType:PersonTypeC];</span><br><span class="line"></span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>,[personA <span class="keyword">class</span>]);</span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>,[personB <span class="keyword">class</span>]);</span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>,[personC <span class="keyword">class</span>]);</span><br><span class="line"></span><br><span class="line">[personA doWork];</span><br><span class="line">[personB doWork];</span><br><span class="line">[personC doWork];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line"><span class="comment">// PersonA</span></span><br><span class="line"><span class="comment">// PersonB</span></span><br><span class="line"><span class="comment">// PersonC</span></span><br><span class="line"><span class="comment">// do PersonA Work</span></span><br><span class="line"><span class="comment">// do PersonB Work</span></span><br><span class="line"><span class="comment">// do PersonC Work</span></span><br></pre></td></tr></table></figure>
<p>这样就只需要传入不同的 Type 就可以实现不同的任务。这种实现模式就叫做“类族模式”。</p>
<h2 id="第10条：在既有类中使用关联对象存放自定义数据"><a href="#第10条：在既有类中使用关联对象存放自定义数据" class="headerlink" title="第10条：在既有类中使用关联对象存放自定义数据"></a>第10条：在既有类中使用关联对象存放自定义数据</h2><p>可以通过“关联对象”这项特性，给某个类关联多个对象，这些对象可以通过 key 区分。在关联对象的时候需要指明对象的“存储策略”，用来维护相应的“内存管理语义”。“存储策略”由 objc_AssociationPolicy 这个枚举维护。下面给出 objc_AssociationPolicy 枚举的取值以及等效的 @property 属性。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Policies related to associative references.</span></span><br><span class="line"><span class="comment"> * These are options to objc_setAssociatedObject()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">typedef</span> OBJC_ENUM(uintptr_t, objc_AssociationPolicy) &#123;</span><br><span class="line">    OBJC_ASSOCIATION_ASSIGN = <span class="number">0</span>,           <span class="comment">/**&lt; Specifies a weak reference to the associated object. */</span></span><br><span class="line">    OBJC_ASSOCIATION_RETAIN_NONATOMIC = <span class="number">1</span>, <span class="comment">/**&lt; Specifies a strong reference to the associated object. </span></span><br><span class="line"><span class="comment">                                            *   The association is not made atomically. */</span></span><br><span class="line">    OBJC_ASSOCIATION_COPY_NONATOMIC = <span class="number">3</span>,   <span class="comment">/**&lt; Specifies that the associated object is copied. </span></span><br><span class="line"><span class="comment">                                            *   The association is not made atomically. */</span></span><br><span class="line">    OBJC_ASSOCIATION_RETAIN = <span class="number">01401</span>,       <span class="comment">/**&lt; Specifies a strong reference to the associated object.</span></span><br><span class="line"><span class="comment">                                            *   The association is made atomically. */</span></span><br><span class="line">    OBJC_ASSOCIATION_COPY = <span class="number">01403</span>          <span class="comment">/**&lt; Specifies that the associated object is copied.</span></span><br><span class="line"><span class="comment">                                            *   The association is made atomically. */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p><img src="http://ovsbvt5li.bkt.clouddn.com/18-4-20/99689322.jpg"><br>对应的3个方法为：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置关联对象</span></span><br><span class="line"><span class="type">void</span> objc_setAssociatedObject(<span class="type">id</span> _Nonnull object, <span class="keyword">const</span> <span class="type">void</span> * _Nonnull key,<span class="type">id</span> _Nullable value, objc_AssociationPolicy policy);</span><br><span class="line"><span class="comment">// 获取关联对象</span></span><br><span class="line"><span class="type">id</span> objc_getAssociatedObject(<span class="type">id</span> _Nonnull object, <span class="keyword">const</span> <span class="type">void</span> * _Nonnull key);                         </span><br><span class="line"><span class="comment">// 移除关联对象</span></span><br><span class="line"><span class="type">void</span> objc_removeAssociatedObjects(<span class="type">id</span> _Nonnull object)   </span><br></pre></td></tr></table></figure>

<blockquote>
<p>系统没有给出移除单个关联对象的接口，如果要移除某个关联对象，可以通过给该关联对象的 key 设置一个空值来实现。<br>void objc_setAssociatedObject(object, key, nil, policy);</p>
</blockquote>
<h4 id="示例"><a href="#示例" class="headerlink" title="示例"></a>示例</h4><p>当我们需要使用 UIAlertView 时，一般会这样写：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)showAlert &#123;</span><br><span class="line">	<span class="built_in">UIAlertView</span> *alertView = [[<span class="built_in">UIAlertView</span> alloc] initWithTitle:<span class="string">@&quot;title&quot;</span> message:<span class="string">@&quot;message&quot;</span> delegate:<span class="keyword">self</span> cancelButtonTitle:<span class="string">@&quot;Cancel&quot;</span> otherButtonTitles:<span class="string">@&quot;Confirm&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line">	[alertView show];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)alertView:(<span class="built_in">UIAlertView</span> *)alertView clickedButtonAtIndex:(<span class="built_in">NSInteger</span>)buttonIndex &#123;</span><br><span class="line">    <span class="keyword">if</span> (buttonIndex == <span class="number">0</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (buttonIndex == <span class="number">1</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当存在多个 UIAlertView 时，委托方法里面就需要对 alertView 进行判断。使用关联对象可以简化这里的逻辑</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="string">&lt;objc/runtime.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="type">void</span> *kAlertKey = <span class="string">@&quot;kAlertKey&quot;</span>;</span><br><span class="line">- (<span class="type">void</span>)showAlert &#123;</span><br><span class="line">	<span class="built_in">UIAlertView</span> *alertView = [[<span class="built_in">UIAlertView</span> alloc] initWithTitle:<span class="string">@&quot;title&quot;</span> message:<span class="string">@&quot;message&quot;</span> delegate:<span class="keyword">self</span> cancelButtonTitle:<span class="string">@&quot;Cancel&quot;</span> otherButtonTitles:<span class="string">@&quot;confirm&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line">	</span><br><span class="line">	<span class="type">void</span> (^block)(<span class="built_in">NSInteger</span>) = ^(<span class="built_in">NSInteger</span> buttonIndex) &#123;</span><br><span class="line">		<span class="keyword">if</span> (buttonIndex == <span class="number">0</span>) &#123;</span><br><span class="line">            </span><br><span class="line">		&#125; <span class="keyword">else</span> <span class="keyword">if</span> (buttonIndex == <span class="number">1</span>) &#123;</span><br><span class="line">            </span><br><span class="line">		&#125;</span><br><span class="line">	&#125;;</span><br><span class="line">	objc_setAssociatedObject(alertView, kAlertKey, block, OBJC_ASSOCIATION_COPY);</span><br><span class="line">	[alertView show];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">void</span>)alertView:(<span class="built_in">UIAlertView</span> *)alertView clickedButtonAtIndex:(<span class="built_in">NSInteger</span>)buttonIndex &#123;</span><br><span class="line">    <span class="type">void</span> (^block)(<span class="built_in">NSInteger</span>) = objc_getAssociatedObject(alertView, kAlertKey);</span><br><span class="line">    block(buttonIndex);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>当关联对象需要捕获了其他变量，可能会造成引用循环。使用关联对象会降低代码的可读性，增加调试的难度。应谨慎使用。</p>
<h2 id="第11条：理解-objc-msgSend-的作用"><a href="#第11条：理解-objc-msgSend-的作用" class="headerlink" title="第11条：理解 objc_msgSend 的作用"></a>第11条：理解 objc_msgSend 的作用</h2><p>给对象发消息</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">id</span> returnValue = [someObject msgName:parameter];</span><br></pre></td></tr></table></figure>
<p>编译器会转换为</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">id</span> returnValue = objc_msgSend(someObject, <span class="keyword">@selector</span>(msgName:), parameter);</span><br></pre></td></tr></table></figure>
<p>objc_msgSend 会在接受者类中搜寻“方法列表”，如果找到对应的方法，则转跳实现代码。如果没找到就沿着继承类向上找。如果最终还是找不到该方法，则进行“消息转发”。同时 objc_msgSend 还会将找到的方法缓存在“快速映射表”，如果下次还需要执行该方法，就会先从“快速映射表”中查找，这样执行起来会快很多。<br>每个类都会有一张类似于字典一样的表格，方法名是 Key ，对应的 Value 则保存着函数指针。objc_msgSend 就是通过这个表格来寻找应该执行的方法并跳转其实现的。这些工作由“动态消息派发系统”来处理。</p>
<h4 id="尾调用优化"><a href="#尾调用优化" class="headerlink" title="尾调用优化"></a>尾调用优化</h4><p>“尾调用”是指一个函数最后一项操作是调用另一个函数，即被调用的函数的返回值就是当前函数的返回值。如果函数在尾部调用的是自身，那么就叫做“尾递归”。<br>尾调用优化是指不需要在当前调用栈上开辟新的栈空间，而是更新原有栈（原有栈的数据已经不需要了），再把调用函数的返回地址替换成当前函数的返回地址。<br>使用“尾调用优化”技术，很大程度上可以避免了栈溢出。  </p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%BA%8C%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0(1)/" class="post-title-link" itemprop="url">《Effective Objective-C 2.0》第二章阅读笔记(1)</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-17 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-17T00:00:00+08:00">2018-04-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:14:25" itemprop="dateModified" datetime="2018-07-01T16:14:25+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第二章：对象、消息、运行期-1"><a href="#第二章：对象、消息、运行期-1" class="headerlink" title="第二章：对象、消息、运行期(1)"></a><center>第二章：对象、消息、运行期(1)</center></h1><p>“对象”是基本构造单元，可以通过对象来存储数据和传递数据。对象之间传递数据并执行任务的过程就叫做“消息传递”。</p>
<h2 id="第6条：理解-“属性”-这一概念"><a href="#第6条：理解-“属性”-这一概念" class="headerlink" title="第6条：理解 “属性” 这一概念"></a>第6条：理解 “属性” 这一概念</h2><p>“属性” 是 Objective-C 的一项特性，用来封装对象中的数据。属性最终是通过实例变量来实现的，属性只是提供了一种简洁的抽象机制。</p>
<h4 id="对象布局"><a href="#对象布局" class="headerlink" title="对象布局"></a>对象布局</h4><p>对象布局在编译期就已经确定了，当代码需要访问实例变量的时候，编译器会把其替换成偏移量，这个偏移量是“硬编码”，表示该变量距离对象内存起始地址有多远。<br>当类增加了实例变量时，原来的偏移量就已经不再适用，所以这时候需要重新编译。偏移量保存在类对象中，会在运行时查找。</p>
<h4 id="应用程序二进制接口（Application-Binary-Interface，ABI）"><a href="#应用程序二进制接口（Application-Binary-Interface，ABI）" class="headerlink" title="应用程序二进制接口（Application Binary Interface，ABI）"></a>应用程序二进制接口（Application Binary Interface，ABI）</h4><blockquote>
<p>应用程序二进制接口描述了应用程序和操作系统之间，一个应用和它的库之间，或者应用的组成部分之间的低层接口。ABI不同于应用程序接口（API），API定义了源代码和库之间的接口，因此同样的代码可以在支持这个API的任何系统中编译，然而ABI允许编译好的目标代码在使用兼容ABI的系统中无需改动就能运行。（百度百科）</p>
</blockquote>
<p>ABI定义了许多内容（标准），其中一项就是生成代码时所应遵循的规范，有了这种规范，我们就可以在分类和实现文件定义实例变量，可以将实例变量从接口文件中移开，以便保护和类实现相关的内部信息。</p>
<h4 id="synthesize-amp-dynamic"><a href="#synthesize-amp-dynamic" class="headerlink" title="@synthesize &amp; @dynamic"></a>@synthesize &amp; @dynamic</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@implementation</span></span></span><br><span class="line"><span class="keyword">@synthesize</span> firstName = _myFirstName;</span><br><span class="line"><span class="keyword">@dynamic</span> firstName;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>@synthesize 用来指定实例变量的名称。<br>@dynamic 告诉编译器不要自动生成实例变量，也不要生成 setter 和 getter 方法。这时编译器不会报错，而是在运行时查找。</p>
<h4 id="属性特质"><a href="#属性特质" class="headerlink" title="属性特质"></a>属性特质</h4><p>原子性，读写权限，内存管理（assign、strong、weak、unsafe_unretained、copy），方法名</p>
<h5 id="原子性"><a href="#原子性" class="headerlink" title="原子性"></a>原子性</h5><p>iOS 开发的时候应该尽量使用 nonatomic，使用 atomic 会严重影响性能。</p>
<h5 id="读写权限"><a href="#读写权限" class="headerlink" title="读写权限"></a>读写权限</h5><p>readwrite 同时生成setter 和 getter 方法。<br>readonly 只生成 getter 方法。  </p>
<h5 id="copy"><a href="#copy" class="headerlink" title="copy"></a>copy</h5><p>当属性类型为 NSString 时，一定要用 copy 修饰，防止当传递过来的值是 NSMutableString 类型，从而可能会在不知情的情况下更改属性的值。</p>
<h2 id="第7条：在对象内部尽量直接访问实例变量（感觉有歧义）"><a href="#第7条：在对象内部尽量直接访问实例变量（感觉有歧义）" class="headerlink" title="第7条：在对象内部尽量直接访问实例变量（感觉有歧义）"></a>第7条：在对象内部尽量直接访问实例变量（感觉有歧义）</h2><p>在对象外面，应该通过属性访问实例变量。在对象内部，除了几种特殊的情况下，读取实例变量应该采用直接访问的形式，设置实例变量则采用属性来设置。</p>
<h4 id="对象内部不要直接设置实例（有歧义）"><a href="#对象内部不要直接设置实例（有歧义）" class="headerlink" title="对象内部不要直接设置实例（有歧义）"></a>对象内部不要直接设置实例（有歧义）</h4><p>这样做不会调用 setter 方法，也就绕过了相关属性定义的“内存管理语义”，比如使用了 copy 特质，直接访问不会拷贝该属性，只会保留新值并释放旧值。此外当设置了KVO时，直接设置实例也不会触发KVO。</p>
<h4 id="初始化时应该直接访问实例"><a href="#初始化时应该直接访问实例" class="headerlink" title="初始化时应该直接访问实例"></a>初始化时应该直接访问实例</h4><p>如果父类初始化使用 setter 方法设置属性，而子类又重写了这个 setter 方法，那么子类初始化时，父类也会初始化，这时父类将会调用子类的 setter 方法。<br>例外：如果待初始化的实例变量申明在父类中，而子类无法直接访问此实例变量，这时就需要调用 setter 方法了。</p>
<blockquote>
<p>dealloc 方法中也应该直接读写实例变量  </p>
</blockquote>
<h4 id="懒加载"><a href="#懒加载" class="headerlink" title="懒加载"></a>懒加载</h4><p>如果某个属性使用了懒加载，那就必须使用 getter 方法了。</p>
<h2 id="第8条：理解-“对象同等性”-这一概念"><a href="#第8条：理解-“对象同等性”-这一概念" class="headerlink" title="第8条：理解 “对象同等性” 这一概念"></a>第8条：理解 “对象同等性” 这一概念</h2><p>“对象同等性” 可以理解为某种意义上两个对象相等，这个“相等”是我们自定义的。官方给我们定义了一些判断两个对象是否“相等”的方法</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSString</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToString:(<span class="built_in">NSString</span> *)aString;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSData</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToData:(<span class="built_in">NSData</span> *)other;</span><br><span class="line"></span><br><span class="line"><span class="comment">// NSDictionary</span></span><br><span class="line">- (<span class="type">BOOL</span>)isEqualToDictionary:(<span class="built_in">NSDictionary</span>&lt;KeyType, ObjectType&gt; *)otherDictionary;</span><br></pre></td></tr></table></figure>

<h4 id="对象完全相等"><a href="#对象完全相等" class="headerlink" title="对象完全相等"></a>对象完全相等</h4><p>用 “&#x3D;&#x3D;” 判断两个对象是否是同一个对象，这里判断的是指针。</p>
<h4 id="自定义-“相等”"><a href="#自定义-“相等”" class="headerlink" title="自定义 “相等”"></a>自定义 “相等”</h4><p>通过 NSObject 协议中的两个方法自定义 “相等”。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">BOOL</span>)isEqual:(<span class="type">id</span>)object;  </span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">readonly</span>) <span class="built_in">NSUInteger</span> hash;</span><br></pre></td></tr></table></figure>
<p>自定义一个 Person 类，包含一个 email 属性。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">Person</span>()</span></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">copy</span>) <span class="built_in">NSString</span> *email;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>

<p>假定对象的 email 属性值相同，就认为这两个类“相同”，那么自定义方法如下：  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">BOOL</span>)isEqualToPerson:(Person *)otherPerson &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="literal">nil</span> == otherPerson) <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> == otherPerson) <span class="keyword">return</span> <span class="literal">YES</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> ([_email isEqualToString:otherPerson.email]) <span class="keyword">return</span> <span class="literal">YES</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (<span class="type">BOOL</span>)isEqual:(<span class="type">id</span>)object &#123;</span><br><span class="line">    <span class="keyword">if</span> ([<span class="keyword">self</span> <span class="keyword">class</span>] != [object <span class="keyword">class</span>]) <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">    </span><br><span class="line">    [<span class="keyword">self</span> isEqualToPerson:object];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NO</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果两个对象相等，则其哈希码一定相同。反之，如果哈希码相同，这两个对象不一定相同。</span></span><br><span class="line"><span class="comment">// 考虑到性能问题，hash 方法要保证高效率</span></span><br><span class="line">- (<span class="built_in">NSUInteger</span>)hash &#123;</span><br><span class="line">	<span class="comment">// 此处逻辑可以自定义</span></span><br><span class="line">    <span class="keyword">return</span> [_email hash];</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="典型应用"><a href="#典型应用" class="headerlink" title="典型应用"></a>典型应用</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// NSArray</span></span><br><span class="line">- (<span class="type">BOOL</span>)containsObject:(ObjectType)anObject;</span><br><span class="line"><span class="comment">// NSSet</span></span><br><span class="line">- (<span class="type">BOOL</span>)containsObject:(ObjectType)anObject;</span><br></pre></td></tr></table></figure>

<p>使用 NSArray 调用 containsObject 这个方法，会直接调用 isEqual 方法判断两个对象是否相等。测试发现这里并没有调用 hash 方法，原因不明，例子如下：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSMutableArray</span> *array = [<span class="built_in">NSMutableArray</span> array];</span><br><span class="line">Person *aPerson = <span class="literal">nil</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">	Person *p = [[Person alloc] initWithEmail:[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;%zd&quot;</span>,i]];</span><br><span class="line">	[array addObject:p];</span><br><span class="line">	aPerson = p;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ([array containsObject:aPerson]) &#123;</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;array has &#x27;aPerson&#x27;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>再使用 NSSet 看看是怎么执行的。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSMutableSet</span> *sets = [<span class="built_in">NSMutableSet</span> set];</span><br><span class="line">Person *aPerson = <span class="literal">nil</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">	Person *p = [[Person alloc] initWithEmail:[<span class="built_in">NSString</span> stringWithFormat:<span class="string">@&quot;%zd&quot;</span>,i]];</span><br><span class="line">	[sets addObject:p];</span><br><span class="line">	aPerson = p;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ([sets containsObject:aPerson]) &#123;</span><br><span class="line">	<span class="built_in">NSLog</span>(<span class="string">@&quot;array has &#x27;aPerson&#x27;&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>NSSet 在 addObject 和 containsObject 方法中都会调用 hash 方法。再 addObject 方法中会调用 isEqual 方法，而 containsObject 方法中则不再调用。NSArray 则是在 containsObject 方法中调用 isEqual 方法。</p>
<blockquote>
<p>不同的集合会使用不同的逻辑判断是否“相等”。</p>
</blockquote>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>在 NSSet 中， hash 方法是判断的第一步，应该保证此方法的高效性，同时也要考虑 <strong>哈希碰撞</strong> 发生的概率。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%E3%80%8AEffective%20Objective-C%202.0%E3%80%8B%E7%AC%AC%E4%B8%80%E7%AB%A0%E9%98%85%E8%AF%BB%E7%AC%94%E8%AE%B0/" class="post-title-link" itemprop="url">《Effective Objective-C 2.0》第一章阅读笔记</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-13 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-13T00:00:00+08:00">2018-04-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:14:08" itemprop="dateModified" datetime="2018-07-01T16:14:08+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="第一章：熟悉-Objective-C-语言"><a href="#第一章：熟悉-Objective-C-语言" class="headerlink" title="第一章：熟悉 Objective-C 语言"></a><center>第一章：熟悉 Objective-C 语言</center></h1><h2 id="第1条：了解-Objective-C-语言的起源"><a href="#第1条：了解-Objective-C-语言的起源" class="headerlink" title="第1条：了解 Objective-C 语言的起源"></a>第1条：了解 Objective-C 语言的起源</h2><h4 id="消息结构"><a href="#消息结构" class="headerlink" title="消息结构"></a>消息结构</h4><p>Objective-C 使用的是“消息结构”（messaging structure）而非“函数调用”（function calling）。<br>使用消息结构的语言，其运行时所执行的代码由运行环境决定。而使用函数调用的语言，则由编译器决定。  </p>
<blockquote>
<p>在C&#x2F;C++中，如果使用的函数是多态，那么运行时会根据“虚方法表”（virtual table）来查找应该执行哪个函数实现。而采用消息结构的语言则都是在运行的时候才查找要执行的方法。</p>
</blockquote>
<h4 id="运行期组件（runtime-component）"><a href="#运行期组件（runtime-component）" class="headerlink" title="运行期组件（runtime component）"></a>运行期组件（runtime component）</h4><p>Objective-C 中重要工作都由运行期组件完成，而非编译器。里面包含了面向对象所需的全部数据结构及函数。其本质是与开发者所编写的代码相链接的动态库。</p>
<h4 id="对象内存分配"><a href="#对象内存分配" class="headerlink" title="对象内存分配"></a>对象内存分配</h4><p>对象所占有的内存总是分配到堆空间（Head）中，而指向对象的指针则是分配到栈（stack）中。分配到堆中的内存必须进行管理，分配到栈上用于保存对象地址的内存，则会在栈帧弹出时自动处理。<br>当遇到非指针类型变量的时候，变量可能会分配到栈空间，比如：结构体。</p>
<h2 id="第2条：在类的头文件中尽量少引用其他头文件"><a href="#第2条：在类的头文件中尽量少引用其他头文件" class="headerlink" title="第2条：在类的头文件中尽量少引用其他头文件"></a>第2条：在类的头文件中尽量少引用其他头文件</h2><h4 id="向前声明（forward-declaring）"><a href="#向前声明（forward-declaring）" class="headerlink" title="向前声明（forward declaring）"></a>向前声明（forward declaring）</h4><p>如果只需要知道有那么一个类名，则不需要引用该类名的头文件（不需要知道其他细节），这时可以向前声明该类，既使用：</p>
<blockquote>
<p>@class className;  </p>
</blockquote>
<p>然后在实现文件中引入该头文件。这样可以降低类与类之间的耦合。<br>引入头文件的时机应该尽量延后，只有当确定要引用该头文件的时候才引用。将大量的头文件引入到头文件中，会增加文件之间的依赖性，从而增加编译时间。   </p>
<h4 id="循环引用"><a href="#循环引用" class="headerlink" title="循环引用"></a>循环引用</h4><p>向前申明可以解决两个类之间的循环引用。文章说道：</p>
<blockquote>
<p>使用 #import 虽然不会导致引用循环，但却意味着两个类有一个不能被正确编译。</p>
</blockquote>
<p>不过，这句话我。。。。无法理解！！！  </p>
<h4 id="头文件需要引用协议"><a href="#头文件需要引用协议" class="headerlink" title="头文件需要引用协议"></a>头文件需要引用协议</h4><p>如果要使用某个协议，则不能使用向前声明，为了不引用整个头文件，可以将协议放到“class-continuation 分类”中，或者单独放到一个文件中，然后使用 #import 引用头文件，这样就不会出现上面说的问题。</p>
<h2 id="第3条：多用字面量语法，少用与之等价的方法"><a href="#第3条：多用字面量语法，少用与之等价的方法" class="headerlink" title="第3条：多用字面量语法，少用与之等价的方法"></a>第3条：多用字面量语法，少用与之等价的方法</h2><p>使用字面量语法可以缩减代码长度，提高代码可读性。也要确保创建对象的时候不能为nil。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSString</span> *string0 = [[<span class="built_in">NSString</span> alloc] initWithString:<span class="string">@&quot;123&quot;</span>];</span><br><span class="line"><span class="built_in">NSString</span> *string1 = <span class="string">@&quot;123&quot;</span>;</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSNumber</span> *number0 = [<span class="built_in">NSNumber</span> numberWithInt:<span class="number">1</span>];</span><br><span class="line"><span class="built_in">NSNumber</span> *number1 = @<span class="number">1</span>;</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSArray</span> *array0 = [<span class="built_in">NSArray</span> arrayWithObjects:<span class="string">@&quot;cat&quot;</span>, <span class="string">@&quot;dog&quot;</span>, <span class="string">@&quot;fish&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSString</span> *cat0 = [array0 objectAtIndex:<span class="number">0</span>];</span><br><span class="line"><span class="built_in">NSArray</span> *array1 = @[<span class="string">@&quot;cat&quot;</span>, <span class="string">@&quot;dog&quot;</span>, <span class="string">@&quot;fish&quot;</span>];</span><br><span class="line"><span class="built_in">NSString</span> *cat1 = array1[<span class="number">0</span>];</span><br><span class="line">    </span><br><span class="line"><span class="built_in">NSDictionary</span> *dictionary0 = [<span class="built_in">NSDictionary</span> dictionaryWithObjectsAndKeys:<span class="string">@&quot;key0&quot;</span>, <span class="string">@&quot;value0&quot;</span>, <span class="string">@&quot;key1&quot;</span>, <span class="string">@&quot;value1&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSString</span> *value0 = [dictionary0 objectForKey:<span class="string">@&quot;key0&quot;</span>];</span><br><span class="line">	</span><br><span class="line"><span class="built_in">NSDictionary</span> *dictionary1 = @&#123;<span class="string">@&quot;key0&quot;</span>:<span class="string">@&quot;value0&quot;</span>, <span class="string">@&quot;key1&quot;</span>:<span class="string">@&quot;value1&quot;</span>&#125;;</span><br><span class="line"><span class="built_in">NSString</span> *value1 = dictionary1[<span class="string">@&quot;key1&quot;</span>];</span><br></pre></td></tr></table></figure>

<h2 id="第4条：多用类型常量，少用-define-预处理指令"><a href="#第4条：多用类型常量，少用-define-预处理指令" class="headerlink" title="第4条：多用类型常量，少用 #define 预处理指令"></a>第4条：多用类型常量，少用 #define 预处理指令</h2><h4 id="使用-define-无法确定类型信息"><a href="#使用-define-无法确定类型信息" class="headerlink" title="使用 #define 无法确定类型信息"></a>使用 #define 无法确定类型信息</h4><p>比如下面的代码用 #define 无法预知 kAnimationDuration 的数据类型，不利于编写开发文档。   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> kAnimationDuration 0.1</span></span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="built_in">NSTimeInterval</span> kAnimationDuration = <span class="number">0.1</span>;</span><br><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> <span class="type">float</span> kAnimationDuration = <span class="number">0.1</span>;</span><br></pre></td></tr></table></figure>

<h4 id="static-const-修饰"><a href="#static-const-修饰" class="headerlink" title="static const 修饰"></a>static const 修饰</h4><p>如果一个变量用 static const 修饰，那么编译器不会创建符号，而是会像 #define 预处理指令一样，在编译的时候将所有的变量替换成常值。</p>
<h4 id="extern-声明全局变量"><a href="#extern-声明全局变量" class="headerlink" title="extern 声明全局变量"></a>extern 声明全局变量</h4><p>使用 static const 修饰的变量只能在本文件内使用，但有时候需要对外公布这个变量，比如该变量作为“通知”的key的时候，此时可以稍微改一下。  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// .h文件 声明一个变量</span></span><br><span class="line"><span class="keyword">extern</span> <span class="built_in">NSString</span> *<span class="keyword">const</span> VCHLoginNotification;</span><br><span class="line"><span class="comment">// .m文件 定义一个变量</span></span><br><span class="line"><span class="built_in">NSString</span> *<span class="keyword">const</span> VCHLoginNotification = <span class="string">@&quot;kLoginNotification&quot;</span>;</span><br></pre></td></tr></table></figure>
<p>这种变量会保存在“全局符号表”中。为了避免命名冲突，这种变量应该加上类名前缀。</p>
<h4 id="判断-const-修饰的是对象还是指针-自己理解"><a href="#判断-const-修饰的是对象还是指针-自己理解" class="headerlink" title="判断 const 修饰的是对象还是指针(自己理解)"></a>判断 const 修饰的是对象还是指针(自己理解)</h4><p>const 修饰的是右边的第一个字符  </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">float</span> <span class="keyword">const</span> valueFloat0 = <span class="number">0.1</span>; <span class="comment">//[1]</span></span><br><span class="line"><span class="keyword">const</span> <span class="type">float</span> valueFloat1 = <span class="number">0.1</span>; <span class="comment">//[2]</span></span><br><span class="line"><span class="built_in">NSString</span> <span class="keyword">const</span> * string0 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[3]</span></span><br><span class="line"><span class="built_in">NSString</span> * <span class="keyword">const</span> string1 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[4]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> * string2 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[5]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> * <span class="keyword">const</span> string3 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[6]</span></span><br><span class="line"><span class="keyword">const</span> <span class="built_in">NSString</span> <span class="keyword">const</span> * string4 = <span class="string">@&quot;abc&quot;</span>; <span class="comment">//[7]</span></span><br></pre></td></tr></table></figure>
<p>[1] const 右边第一个字符是 valueFloat0，表示 valueFloat0 里面的值是不变的。valueFloat0  不能是左值。<br>[2] const 右边第一个字符是 float，而 float 指的就是 valueFloat1，所以 valueFloat1 的值是不变的。valueFloat1 不能是左值。<br>[3] const 右边第一个字符是 string0，string0 是一个指针，所以 string0 指向的地址是不变的。string0 不能是左值。<br>[4] const 右边第一个字符是 string1（指针），所以 string1 指向的地址是不变的。string1 不能是左值。<br>[5] const 右边第一个字符是 NSString，表示的是 @”abc” 这个对象，所以 @”abc 是不可变对象。不可以通过 string2 这个指针来修改它指向的对象的内容。(这里刚好 @”abc” 是不能修改的，就算指向的对象是可以被修改的，也不能通过 const 修饰的指针去修改)<br>[6] 第一个 const 右边第一个字符是 NSString， 等同于 [5]。第二个 const 等同于 [4]。<br>[7] 等同于 [6]  </p>
<h2 id="第5条：用枚举表示状态、选项、状态码"><a href="#第5条：用枚举表示状态、选项、状态码" class="headerlink" title="第5条：用枚举表示状态、选项、状态码"></a>第5条：用枚举表示状态、选项、状态码</h2><p>枚举可以提高代码可读性。   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 状态、状态码</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">NS_ENUM</span>(<span class="built_in">NSInteger</span>, <span class="built_in">UIViewAnimationTransition</span>) &#123;</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionNone</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionFlipFromLeft</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionFlipFromRight</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionCurlUp</span>,</span><br><span class="line">    <span class="built_in">UIViewAnimationTransitionCurlDown</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 可组合选项</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="built_in">NS_OPTIONS</span>(<span class="built_in">NSUInteger</span>, <span class="built_in">UIViewAutoresizing</span>) &#123;</span><br><span class="line">    <span class="built_in">UIViewAutoresizingNone</span>                 = <span class="number">0</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleLeftMargin</span>   = <span class="number">1</span> &lt;&lt; <span class="number">0</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleWidth</span>        = <span class="number">1</span> &lt;&lt; <span class="number">1</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleRightMargin</span>  = <span class="number">1</span> &lt;&lt; <span class="number">2</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleTopMargin</span>    = <span class="number">1</span> &lt;&lt; <span class="number">3</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleHeight</span>       = <span class="number">1</span> &lt;&lt; <span class="number">4</span>,</span><br><span class="line">    <span class="built_in">UIViewAutoresizingFlexibleBottomMargin</span> = <span class="number">1</span> &lt;&lt; <span class="number">5</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>enum 用来表示状态，options 用来表示可组合的选项。</p>
<h4 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h4><p>1、用枚举处理 switch 的时候不要实现 default 分支。这样加入新的分支后，编译器就会提示开发者。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BC%96%E8%AF%91%E6%97%B6%E4%B8%8E%E8%BF%90%E8%A1%8C%E6%97%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%BC%96%E8%AF%91%E6%97%B6%E4%B8%8E%E8%BF%90%E8%A1%8C%E6%97%B6/" class="post-title-link" itemprop="url">iOS基础之编译时与运行时</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-11 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-11T00:00:00+08:00">2018-04-11</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:13:31" itemprop="dateModified" datetime="2018-07-01T16:13:31+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">iOS基础</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="序言"><a href="#序言" class="headerlink" title="序言"></a>序言</h1><p>从开始学iOS就看到这样的一个例子，也是面试题，但我一直都觉得这题目没什么意义，最初设计这题目的人目的是什么？想让人了解什么是编译时什么是运行时？不解！不管了，以后应该会了解的。   </p>
<h3 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h3><blockquote>
<p><strong>string在编译时和运行时分别时什么类型的对象?</strong><br><strong>NSString *string &#x3D; [[NSDate alloc] init]; &#x2F;&#x2F; 原题是 NSData，我改为 NSDate，方便我后面发消息</strong>   </p>
</blockquote>
<p>直接这样写编译器会报警告！  </p>
<blockquote>
<p>Incompatible pointer types initializing ‘NSString *‘ with an expression of type ‘NSDate *‘</p>
</blockquote>
<p>可以使用类型转换消除这个警告   </p>
<blockquote>
<p><strong>NSString *string &#x3D; (NSString *)[[NSDate alloc] init];</strong></p>
</blockquote>
<p>此时编译器已经没有任何警告了，然后我们给 “string” 这个对象发消息看看会出现什么情况   </p>
<h4 id="直接调用方法"><a href="#直接调用方法" class="headerlink" title="直接调用方法"></a>直接调用方法</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSString</span> *string = (<span class="built_in">NSString</span> *)[[<span class="built_in">NSDate</span> alloc] init];</span><br><span class="line"><span class="comment">//调用 NSString 的方法，编译通过</span></span><br><span class="line">[string stringByAppendingString:<span class="string">@&quot;abc&quot;</span>];</span><br><span class="line"><span class="comment">//调用 NSDate 的方法，编译不通过</span></span><br><span class="line"><span class="comment">//提示：No visible @interface for &#x27;NSString&#x27; declares the selector &#x27;isEqualToDate:&#x27;</span></span><br><span class="line">[string isEqualToDate:[<span class="built_in">NSDate</span> date]];</span><br></pre></td></tr></table></figure>
<p>从上面提示的注释信息可以看出，编译器认为 “string” 就是 NSString 类型的对象。调用 NSDate 的方法编译不通过。<br>然后，运行Demo，结果程序直接崩溃，提示：<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-4-12/15455244.jpg"></p>
<blockquote>
<p>-[_NSZeroData stringByAppendingString:]: unrecognized selector sent to instance 0x1010d12e0</p>
</blockquote>
<p>显然程序是找不到 “stringByAppendingString” 方法才崩溃的。</p>
<h4 id="通过-performSelector-调用方法"><a href="#通过-performSelector-调用方法" class="headerlink" title="通过 performSelector 调用方法"></a>通过 performSelector 调用方法</h4><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSString</span> *string = (<span class="built_in">NSString</span> *)[[<span class="built_in">NSDate</span> alloc] init];</span><br><span class="line"><span class="comment">//编译通过，运行崩溃</span></span><br><span class="line">[string performSelector:<span class="keyword">@selector</span>(stringByAppendingString:) withObject:<span class="string">@&quot;abc&quot;</span> afterDelay:<span class="number">0</span>];</span><br><span class="line"><span class="comment">//编译通过，运行通过</span></span><br><span class="line">[string performSelector:<span class="keyword">@selector</span>(isEqualToDate:) withObject:[<span class="built_in">NSDate</span> date] afterDelay:<span class="number">0</span>];</span><br></pre></td></tr></table></figure>

<p>通过 performSelector 给 “string” 对象发 “stringByAppendingString” 消息，依然是崩溃。发 “isEqualToDate” 消息，成功。</p>
<h4 id="结论"><a href="#结论" class="headerlink" title="结论"></a>结论</h4><p>在编译的时候 “string” 是 NSString 类型的对象，所以给 “string” 对象发送 NSString 特有的消息可以通过编译。<br>而在运行的时候 “string” 是 NSDate 类型的对象，这就是为什么给 “string” 对象发送 “stringByAppendingString” 消息会崩溃，而 发送 “isEqualToDate” 消息则成功的原因。<br>从下图也可以看出运行的时候的类型为 NSDate<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-4-12/78772051.jpg"></p>
<h3 id="编译时-amp-运行时"><a href="#编译时-amp-运行时" class="headerlink" title="编译时 &amp; 运行时"></a>编译时 &amp; 运行时</h3><p>编译时类型由声明该变量时使用的类型决定，运行时类型由实际赋给该变量的对象决定。<br>编译时会对语言进行语法检测，并编译成机器语言，由于OC的动态性，代码能否执行成功还得到运行时才能检测出来。<br>运行时会把编译好的代码装到内存中运行，这时候会对对象的类型、方法等进行检测，如果检测失败可能会直接崩溃。  </p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/iOS%E5%BC%80%E5%8F%91%E4%B9%8B%E7%90%86%E8%A7%A3load%E5%92%8Cinitialize/" class="post-title-link" itemprop="url">iOS开发之理解load和initialize</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-10 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-10T00:00:00+08:00">2018-04-10</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:13:16" itemprop="dateModified" datetime="2018-07-01T16:13:16+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="load"><a href="#load" class="headerlink" title="load"></a>load</h2><p>load 会在类装载的时候调用（main函数执行之前）。load 不会被覆盖，如果父类、父类分类、子类、子类分类，同时实现了 load 方法，那么这些方法都会执行。</p>
<h3 id="调用顺序"><a href="#调用顺序" class="headerlink" title="调用顺序"></a>调用顺序</h3><p>1、先调用父类的 load 方法，再调用子类的 load 方法。<br>2、先调用本类的 load 方法，再调用分类的 load 方法。</p>
<h3 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h3><p>1、Method Swizzle 。</p>
<h2 id="initialize"><a href="#initialize" class="headerlink" title="initialize"></a>initialize</h2><p>initialize 会在第一次给该类发送消息之前调用，有些文章说是在实例化、初始化之前调用是错的。看看文档是怎么说的</p>
<blockquote>
<p><strong>Initializes the class before it receives its first message.</strong>   </p>
</blockquote>
<h3 id="调用顺序-1"><a href="#调用顺序-1" class="headerlink" title="调用顺序"></a>调用顺序</h3><p>父类优先于子类调用 initialize 方法。<br>如果子类以及子类的分类没有实现 initialize 方法，那么当第一次给子类发消息的时候，会先给父类的 initialize 发消息。也就是父类的 initialize 方法可能会被调用多次。<br>如果本类以及其分类都实现 initialize 方法，那么只会调用 分类的 initialize 方法。</p>
<h3 id="线程安全"><a href="#线程安全" class="headerlink" title="线程安全"></a>线程安全</h3><p>initialize 是线程安全的，自带锁，当第一个线程给这个类发了 initialize 消息，其他想给这个类发 initialize 消息的线程会被阻塞，直到第一个线程发送完 initialize 消息。</p>
<h3 id="问题"><a href="#问题" class="headerlink" title="问题"></a>问题</h3><p><strong>1、如果本类以及本类的多个分类都实现了 initialize 方法，怎么调用？</strong><br>答：会调用 Compile Source 中的本类最后一个分类的 initialize 方法，如下图：<br><img src="http://ovsbvt5li.bkt.clouddn.com/18-4-11/38950580.jpg"><br>我在代码中实现三个 initialize 方法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Person</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Person (Special)</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person (Special) initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Person (Special1)</span></span><br><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Person (Special1) initialize.......&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果打印出”<strong>Person (Special1) initialize…….</strong>“。<br>当我在 Compile Source 中调换了本类两个分类的先后顺序后，则打印出”<strong>Person (Special) initialize…….</strong>“。<br>从而得出结论上面的结论，Compile Source 中本类最后一个分类的 initialize 方法将会被调用。</p>
<p><strong>2、当子类及其分类没有实现 initialize 方法，在父类的 initialize 方法中怎么区分这个消息是通过本类发来的还是子类发来的？</strong><br>这里我定义了两个类，Person 为父类，Student 为子类。Student 类中没有实现 initialize 方法。那么给 Student 发消息后，结果如下：   </p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">+ (<span class="type">void</span>)initialize &#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span> == [Person <span class="keyword">self</span>]) &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;本类发来的 initialize 消息。%@ - %@&quot;</span>,<span class="keyword">self</span>,[Person <span class="keyword">self</span>]);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;子类发来的 initialize 消息。%@ - %@&quot;</span>,<span class="keyword">self</span>,[Person <span class="keyword">self</span>]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>打印结果：<br>本类发来的 initialize 消息。Person - Person<br>子类发来的 initialize 消息。Student - Person  </p>
</blockquote>
<p>既：如果是本类发送的 initialize 消息，那么 self &#x3D;&#x3D; Person。如果是子类发送过来的消息，那么 self &#x3D;&#x3D; Student。   </p>
<h3 id="使用场景-1"><a href="#使用场景-1" class="headerlink" title="使用场景"></a>使用场景</h3><p>1、初始化静态变量。</p>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><p>1、由于 initialize 使用的是阻塞的调用方式，当一个类 initialize 依赖 另一个类的 initialize 的时候，容易造成死锁，所以应该尽量避免在 initialize 中完成一些复杂的初始化工作。<br>2、应该避免问题1这样的情况出现。如果需要在本类以及分类中同时实现初始化，可以考虑用 load 方法。</p>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/[%E7%AE%97%E6%B3%95]%E7%BB%99%E5%AE%9A%E5%B7%B2%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%EF%BC%8C%E6%89%BE%E5%87%BA%E5%92%8C%E4%B8%BA%E7%89%B9%E5%AE%9A%E6%95%B0%E5%80%BC%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%95%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%5B%E7%AE%97%E6%B3%95%5D%E7%BB%99%E5%AE%9A%E5%B7%B2%E6%8E%92%E5%BA%8F%E6%95%B0%E7%BB%84%EF%BC%8C%E6%89%BE%E5%87%BA%E5%92%8C%E4%B8%BA%E7%89%B9%E5%AE%9A%E6%95%B0%E5%80%BC%E7%9A%84%E4%B8%A4%E4%B8%AA%E6%95%B0/" class="post-title-link" itemprop="url">给定已排序数组，找出和为特定数值的两个数</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-08 22:02:01" itemprop="dateCreated datePublished" datetime="2018-04-08T22:02:01+08:00">2018-04-08</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:12:51" itemprop="dateModified" datetime="2018-07-01T16:12:51+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h1 id="要求"><a href="#要求" class="headerlink" title="要求"></a>要求</h1><p>给定已排序数组，找出和为特定数值的两个数。假定数组中的数值都不相同。</p>
<h3 id="方法一：穷举法"><a href="#方法一：穷举法" class="headerlink" title="方法一：穷举法"></a>方法一：穷举法</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)fineTwoNumberWithArray0:(<span class="type">int</span> *)nums count:(<span class="type">int</span>)count target:(<span class="type">int</span>)target &#123;</span><br><span class="line">    <span class="type">int</span> leftNum,rightNum;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; count - <span class="number">1</span>; i++) &#123;</span><br><span class="line">        leftNum = nums[i];</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> j = i + <span class="number">1</span>; j &lt; count; j++) &#123;</span><br><span class="line">            rightNum = nums[j];</span><br><span class="line">            <span class="keyword">if</span> ((rightNum + leftNum) == target) &#123;</span><br><span class="line">                <span class="built_in">NSLog</span>(<span class="string">@&quot;%d + %d = %d&quot;</span>,leftNum, rightNum, target);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>T(n) &#x3D; (n - 1 + 1) * n &#x2F; 2 &#x3D; (n^2) &#x2F; 2 &#x3D; O(n^2)，即时间复杂度：O(n^2)。   </p>
</blockquote>
<h3 id="方法二"><a href="#方法二" class="headerlink" title="方法二"></a>方法二</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)fineTwoNumberWithArray1:(<span class="type">int</span> *)nums count:(<span class="type">int</span>)count target:(<span class="type">int</span>)target &#123;</span><br><span class="line">    <span class="type">int</span> left = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> right = count - <span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span> sum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span>(left &lt;= right) &#123;</span><br><span class="line">        sum = nums[left] + nums[right];</span><br><span class="line">        <span class="keyword">if</span> (sum &lt; target) &#123;</span><br><span class="line">            left += <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (sum &gt; target) &#123;</span><br><span class="line">            right -= <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@&quot;%d + %d = %d&quot;</span>,nums[left], nums[right], target);</span><br><span class="line">            left += <span class="number">1</span>;</span><br><span class="line">            right -= <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>T(n) &lt;&#x3D; n - 1 &#x3D; O(n) 时间复杂度：O(n)。 </p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




    


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/04/2018/04/%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="undefined | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          <a href="/2018/04/2018/04/%E6%97%B6%E9%97%B4%E5%A4%8D%E6%9D%82%E5%BA%A6/" class="post-title-link" itemprop="url">时间复杂度</a>
        </h2>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-04-08 20:00:04" itemprop="dateCreated datePublished" datetime="2018-04-08T20:00:04+08:00">2018-04-08</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-01 16:13:02" itemprop="dateModified" datetime="2018-07-01T16:13:02+08:00">2018-07-01</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
          <h2 id="时间复杂度"><a href="#时间复杂度" class="headerlink" title="时间复杂度"></a>时间复杂度</h2><p>一个算法需要执行的次数我们记为T(n)，其中n为算法的规模。现在引入某个辅助函数f(n)，当n趋近于无穷大时，T(n)&#x2F;f(n) &#x3D; C (C ≠ 0)。则f(n)和T(n)是同量级函数，记为T(n) &#x3D; O(f(n))，我们称这个为时间复杂度。</p>
<p>##每种时间复杂度表示的意思</p>
<h3 id="T-n-x3D-O-1"><a href="#T-n-x3D-O-1" class="headerlink" title="T(n) &#x3D; O(1)"></a>T(n) &#x3D; O(1)</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)aFunction0:(<span class="type">int</span>)n &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;%zd&quot;</span>,n); <span class="comment">// 执行 1 次</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>不管输入的n是多少，执行次数都是常数。执行次数和输入n值没有任何关系。<br>T(n) &#x3D; 1 &#x3D; O(1)</p>
</blockquote>
<h3 id="T-n-x3D-O-n"><a href="#T-n-x3D-O-n" class="headerlink" title="T(n) &#x3D; O(n)"></a>T(n) &#x3D; O(n)</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)aFunction1:(<span class="type">int</span>)n &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123; <span class="comment">// n + 1 次</span></span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;%zd&quot;</span>,i); <span class="comment">// n 次</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>执行次数和输入的n值成线性关系。<br>T(n) &#x3D; n + 1 + n &#x3D; 2n + 1 &#x3D; O(n)</p>
</blockquote>
<h3 id="T-n-x3D-O-n-2"><a href="#T-n-x3D-O-n-2" class="headerlink" title="T(n) &#x3D; O(n^2)"></a>T(n) &#x3D; O(n^2)</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">void</span>)aFunction2:(<span class="type">int</span>)n &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123; <span class="comment">// n + 1</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> j = <span class="number">0</span>; j &lt; n; j++) &#123; <span class="comment">// n + 1</span></span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@&quot;%zd&quot;</span>,i); <span class="comment">// n</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>执行次数和输入的n值成线性关系。<br>T(n) &#x3D; (n + 1) * (n + 1 + n) &#x3D; 2n^2 + 3n + 1 &#x3D; O(n^2)</p>
</blockquote>
<h3 id="T-n-x3D-O-log-n"><a href="#T-n-x3D-O-log-n" class="headerlink" title="T(n) &#x3D; O(log(n))"></a>T(n) &#x3D; O(log(n))</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="type">int</span>)aFunction3:(<span class="type">int</span> *)nums count:(<span class="type">int</span>)count target:(<span class="type">int</span>)target &#123;</span><br><span class="line">    <span class="type">int</span> left = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> right = count - <span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span> mid = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span>(left &lt;= right) &#123;</span><br><span class="line">        mid = (left + right) &gt;&gt; <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">if</span> (nums[mid] &lt; target) &#123;</span><br><span class="line">            left = mid + <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (nums[mid] &gt; target) &#123;</span><br><span class="line">            right = mid - <span class="number">1</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> mid;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第1次查找，找到的概率为 1&#x2F;n<br>第2次查找，找到的概率为 2&#x2F;n<br>第3次查找，找到的概率为 4&#x2F;n<br>第m次查找，找到的概率为 2^(m - 1)&#x2F;n<br>假设最多需要查找m次，那么存在：1&#x2F;n + 2&#x2F;n + 4&#x2F;n + … + 2^(m - 1)&#x2F;n &#x3D; 1，可以推导出 m &lt;&#x3D; lg(n + 1)<br>即 T(n) &#x3D; O(log(n))</p>
</blockquote>
<h3 id="T-n-x3D-O-nlog-n"><a href="#T-n-x3D-O-nlog-n" class="headerlink" title="T(n) &#x3D; O(nlog(n))"></a>T(n) &#x3D; O(nlog(n))</h3><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 快速排序</span></span><br><span class="line">- (<span class="type">void</span>)quickSort:(<span class="type">int</span> *)nums count:(<span class="type">int</span>)count &#123;</span><br><span class="line">    <span class="type">int</span> start = <span class="number">0</span>;</span><br><span class="line">    <span class="type">int</span> end = count - <span class="number">1</span>;</span><br><span class="line">    <span class="type">int</span> value = nums[start];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">if</span> (count &lt; <span class="number">1</span>) <span class="keyword">return</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> (start &lt; end) &#123;</span><br><span class="line">        <span class="comment">//从数组右边往左查找一个小于value的元素</span></span><br><span class="line">        <span class="keyword">while</span> (start &lt; end) &#123;</span><br><span class="line">            <span class="keyword">if</span> (nums[end] &lt; value) &#123;</span><br><span class="line">                nums[start] = nums[end];</span><br><span class="line">                start++;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                end--;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//从数组左边往右查找一个大于value的元素</span></span><br><span class="line">        <span class="keyword">while</span> (start &lt; end) &#123;</span><br><span class="line">            <span class="keyword">if</span> (nums[start] &gt; value) &#123;</span><br><span class="line">                nums[end] = nums[start];</span><br><span class="line">                end--;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                start++;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    nums[start] = value;</span><br><span class="line">    </span><br><span class="line">    [<span class="keyword">self</span> quickSort:nums count:start];</span><br><span class="line">    [<span class="keyword">self</span> quickSort:nums + start + <span class="number">1</span> count:count - start - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>第1次递归：T[n] &#x3D; 2T[n&#x2F;2] + n<br>第2次递归：T[n] &#x3D; 2{ 2T[n&#x2F;4] + (n&#x2F;2) }  + n &#x3D; 2^2 T[n&#x2F;(2^2)] + 2n<br>第m次递归：T[n] &#x3D; 2^m T[n&#x2F;(2^m)] + mn<br>假设最多需要m次递归完，那么：T[n&#x2F;(2^m)] &#x3D; T(1)  &#x3D;&#x3D;&gt; m &#x3D; log2(n)<br>得到：T[n] &#x3D; 2^m T[1] + mn &#x3D; 2^(log2(n))T[1] + (log2(n))n &#x3D; nT[1] + (log2(n))n<br>当n趋近于无穷大的时候 T[n] &#x3D; nT[1] + (log2(n))n &#x3D; (log2(n))n &#x3D; O(nlogn)<br>即：T(n) &#x3D; O(nlog(n))   </p>
</blockquote>

      
    </div>

    
    
    

    <footer class="post-footer">
        <div class="post-eof"></div>
      
    </footer>
  </article>
</div>




  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/6/"><i class="fa fa-angle-left" aria-label="Previous page"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/6/">6</a><span class="page-number current">7</span><a class="page-number" href="/page/8/">8</a><span class="space">&hellip;</span><a class="page-number" href="/page/10/">10</a><a class="extend next" rel="next" href="/page/8/"><i class="fa fa-angle-right" aria-label="Next page"></i></a>
  </nav>

</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
